package com.gem.talkbase.activity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;

import com.aps.l;
import com.gem.talkbase.R;
import com.gem.talkbase.adapter.RecentChatAdapter;
import com.gem.talkbase.bean.ChatMsg;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.fragment.Fragment_contact;
import com.gem.talkbase.fragment.Fragment_message;
import com.gem.talkbase.service.JSON_Friend_info;
import com.gem.talkbase.service.JSON_GetFirend_Unick;
import com.gem.talkbase.util.MessageDB;
import com.gem.talkbase.util.MyDate;
import com.gem.talkbase.util.XmppTool;
import com.gem.talkbase.widget.SwipeListView;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;


public class ChatMessageService extends Service {
	RecentChatAdapter recentChatAdapter;
	private SwipeListView mSwipeListView;
	private List<ChatMsg> listMsg =new ArrayList<ChatMsg>();
	private MessageDB messageDB;
	private ChatManager cm;
	private List<Firend> list;
	String name =null,userimage,name1,image1;
	private BroadcastReceiver receiver ;
	Firend firend = null;
    private String requestPath=Client.Firend_unick_image,messageBody,whosend;
    private String requestPath2=Client.GetFirendunick;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
    
	@Override
	public boolean stopService(Intent name) {
		// TODO Auto-generated method stub
		return super.stopService(name);
	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	@Override
	public void onCreate() {
		super.onCreate();
		if (android.os.Build.VERSION.SDK_INT > 9) {
		    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		    StrictMode.setThreadPolicy(policy);
		}
		messageDB = new MessageDB(this);
		cm = XmppTool.getConnection().getChatManager();

		
		cm.addChatListener(new ChatManagerListener() {
			@Override
			public void chatCreated(Chat chat, boolean able) {

				chat.addMessageListener(new MessageListener() {
					@Override
					public void processMessage(Chat chat2, Message message) {
    
						System.out.println("???????????????????????????????????????????????????????????????");
						 messageBody = message.getBody();
						if(messageBody != null){
						String from = message.getFrom();
						whosend = from.substring(0, from.lastIndexOf("@"));
						String time = MyDate.getDateEN();
						ChatMsg entity = new ChatMsg(whosend,messageBody,
								time,"IN");
						messageDB.saveMsg(whosend, entity);// 保存到数据库
						info(whosend, messageBody);
		//	=================================================================================	
//					     Fragment_message fragment_message=new Fragment_message();
//						 Bundle bundle=new Bundle();
//						 bundle.putString("friendid", whosend);//绑定登录id号
////						 bundle.putString("msg", messageBody);
////						 bundle.putString("date", time);
//						 fragment_message.setArguments(bundle);
//						listMsg.add(entity);
//						Fragment_message.fun(listMsg);
		//=======================================================================================				
						
						 //把收到的消息已广播的形式发送出去
						Intent intent = new Intent();
						intent.setAction("com.gem.talkbase");
						intent.putExtra("message", entity);
						sendBroadcast(intent);
						
					
//						
//						 listMsg.add(entity);
//						 Fragment_message.fun(listMsg);
//						 System.out.println("listMsg============================"+listMsg);
//						 Bundle bundle=new Bundle();
//						 bundle.putString("friendid", whosend);//绑定登录id号
//						 bundle.putString("msg", messageBody);
//						 bundle.putString("date", time);
//						 fragment_message.setArguments(bundle);
					   } 
					}
				});
			}
		});
	}
   
	@Override
	public void onDestroy() {
		super.onDestroy();
		
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);;

//		cm.addChatListener(new ChatManagerListener() {
//			@Override
//			public void chatCreated(Chat chat, boolean able) {
//
//				chat.addMessageListener(new MessageListener() {
//					@Override
//					public void processMessage(Chat chat2, Message message) {
//    
//						System.out.println("???????????????????????????????????????????????????????????????");
//						 messageBody = message.getBody();
//						if(messageBody != null){
//						String from = message.getFrom();
//						whosend = from.substring(0, from.lastIndexOf("@"));
//						String time = MyDate.getDateEN();
//						ChatMsg entity = new ChatMsg(whosend,messageBody,
//								time,"IN");
//						messageDB.saveMsg(whosend, entity);// 保存到数据库
//						info(whosend, messageBody);
//		//	=================================================================================	
////					     Fragment_message fragment_message=new Fragment_message();
////						 Bundle bundle=new Bundle();
////						 bundle.putString("friendid", whosend);//绑定登录id号
//////						 bundle.putString("msg", messageBody);
//////						 bundle.putString("date", time);
////						 fragment_message.setArguments(bundle);
////						listMsg.add(entity);
////						Fragment_message.fun(listMsg);
//		//=======================================================================================				
//						
//						 //把收到的消息已广播的形式发送出去
//						Intent intent = new Intent();
//						intent.setAction("com.gem.talkbase");
//						intent.putExtra("message", entity);
//						sendBroadcast(intent);
//						
//					
////						
////						 listMsg.add(entity);
////						 Fragment_message.fun(listMsg);
////						 System.out.println("listMsg============================"+listMsg);
////						 Bundle bundle=new Bundle();
////						 bundle.putString("friendid", whosend);//绑定登录id号
////						 bundle.putString("msg", messageBody);
////						 bundle.putString("date", time);
////						 fragment_message.setArguments(bundle);
//					   } 
//					}
//				});
//			}
//		});
	}
	public void info(final String username,final String mess){
		AjaxParams params = new AjaxParams();
		params.put("firend_id", username);
		FinalHttp fh = new FinalHttp();
		fh.post(requestPath2, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}
			@Override
			public void onSuccess(String jsonString) {
	 			super.onSuccess(jsonString);
                System.out.println(jsonString+"===========得到昵称的json");
	 			list=new ArrayList<Firend>();
				JSON_GetFirend_Unick json_GetFirend_Unick=new JSON_GetFirend_Unick();
				list=json_GetFirend_Unick.info(jsonString);
				Iterator<Firend> iterator=list.iterator();
				String unick=null;
				while (iterator.hasNext()) {
					Firend firend = (Firend) iterator.next();
				    unick =firend.getUnick();
				} 
				fun(username,unick,mess);//调用通知的方法。
			}
		 });
	}
      public void fun(String username,String name ,String mes){
    	  
    	  ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);  
    	  List<ActivityManager.RunningTaskInfo> list =  am.getRunningTasks(2)  ;
    	  ComponentName c=list.get(0).topActivity ;
  		  String s1  = c.getClassName() ;
  		  //s1为当前用户操作的界面   s1= 包名+当前Activity名
          //如果用户当前界面在聊天会话界面 ，则不会弹出通知信息
    	  if(!("com.gem.talkbase.activity.Chat_Activity".equals(s1))) {
    	  
    	  System.out.println("######################################################");
    	
    	  NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  		   
  		  //得到通知      notificaString 是快速显示在屏幕最上方的，然后很快消失
  	      Notification notification = new Notification( R.drawable.talknotification, name+"发来一条消息" , System.currentTimeMillis()) ;
  	    
    	    //点击通知的内容 ，跳转到Myactivity
    	  Intent notificationIntent = new Intent(ChatMessageService.this, Chat_Activity.class);
    	  notificationIntent.putExtra("user_name",username);//好友id
          PendingIntent contentIntent = PendingIntent.getActivity(ChatMessageService.this, 0, notificationIntent, 0)  ;
          
          //如果点击通知后不做任何操作 ，则把contentIntent设置为null
    	  notification.setLatestEventInfo(ChatMessageService.this,name+"发来一条消息", mes , contentIntent)  ;  
    	  notification.flags  = Notification.FLAG_AUTO_CANCEL ;          //点击会自动消失
    	   
    	  notification.defaults = notification.DEFAULT_SOUND ;        
    	 //DEFAULT_SOUND 通知来的时候，会调用系统的铃声，测试的结果是手机短信声音
    	  
    	  //清除原来的通知
    	  notificationManager.cancel(0);
    	  notificationManager.notify( 0 , notification) ;	  
    	  }
      }
	
}
